package com.theatre.userservice.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.theatre.userservice.exception.BusinessException;
import com.theatre.userservice.mapper.UserMapper;
import com.theatre.userservice.model.dto.PasswordDTO;
import com.theatre.userservice.model.dto.UserLoginDTO;
import com.theatre.userservice.model.entity.User;
import com.theatre.userservice.model.vo.UserLoginVO;
import com.theatre.userservice.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
@Service
public class UserServiceImpl  extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public void changePassword(PasswordDTO passwordDTO) {
        // 1. 根据用户ID查出数据库中原有用户
        User user = this.getById(passwordDTO.getUserId());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 2. 对前端传来的旧密码进行MD5加密
        String oldPwdMd5 = DigestUtils.md5DigestAsHex(passwordDTO.getOldPassword().getBytes());

        // 3. 比对数据库中保存的加密密码
        if (!oldPwdMd5.equals(user.getPassword())) {
            throw new RuntimeException("旧密码错误");
        }

        // 4. 对新密码进行MD5加密并更新
        String newPwdMd5 = DigestUtils.md5DigestAsHex(passwordDTO.getNewPassword().getBytes());
        user.setPassword(newPwdMd5);
        this.updateById(user);
    }
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        // 1. 根据用户名查出数据库中用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StrUtil.contains(userLoginDTO.getAccount(), "@")) {
            // 认为是邮箱
            queryWrapper.eq("email", userLoginDTO.getAccount());
        } else {
            // 认为是用户名
            queryWrapper.eq("username", userLoginDTO.getAccount());
        }
        User user = this.getOne(queryWrapper, false);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        // 2. 对前端传来的密码进行MD5加密
        String pwdMd5 = DigestUtils.md5DigestAsHex(userLoginDTO.getPassword().getBytes());
        // 3. 比对数据库中保存的加密密码
        if (!pwdMd5.equals(user.getPassword())) {
            throw new BusinessException("密码错误");
        }
        return user;
    }
}
